import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/custompage/msg_history_page.dart';
import 'package:find_friend/pages/im/custompage/msg_mod_group.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/mine_background.dart';
import 'package:find_friend/pages/mine/mine_info.dart';
import 'package:find_friend/pages/mine/mine_preview_page.dart';
import 'package:find_friend/pages/mine/mine_setting/setting_notifier.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:soundpool/soundpool.dart';

import 'msg_historyimg_page.dart';

class MsgSettingPage extends StatefulWidget {
  
  final SharedUserInfo userInfo;
  final Function(String remarkName) onModRemarkName;// 修改备注回调

  const MsgSettingPage({Key key, this.userInfo, this.onModRemarkName}) : super(key: key);

  @override
  _MsgSettingPageState createState() => _MsgSettingPageState();
}

class _MsgSettingPageState extends State<MsgSettingPage> {

  bool isupdate = false;
  String groupName = "";
  bool notifierOpen = false;
  bool isspecialSound = false;
  String username;
  static const String Key_notifer = "Key_notifer";

  @override
  void initState() {
    super.initState();

    groupName = widget.userInfo.friendgroup;
    username = widget.userInfo.remarkname;

    SharedPreferences.getInstance().then((value){
      bool val = value.getBool(Key_notifer + widget.userInfo.mobile);

      if(val != null) {
        setState(() {
          notifierOpen = val;
          isspecialSound = value.getStringList(KEY_special_sound)?.contains(widget.userInfo.mobile) ?? false;
        });
      }
    });
                      
  }

  _requestDel() {
    RongcloudImPlugin.deleteMessages(RCConversationType.Private, widget.userInfo.mobile, (code) => null);
    Networktool.request(API.friend, params: {"mobile":widget.userInfo.mobile}, method: NETWORKHTTPMethod.DELETE, success: (data){
      int count = 0;
      Navigator.of(context).popUntil((_) => count++ >= 2);
    });
  }

  /// 播放音频
  void _playAudio() async {
    
    Soundpool pool = Soundpool(streamType: StreamType.notification);
    int soundId = await rootBundle.load("assets/audio/notice.mp3").then((value){
      return pool.load(value);
    });
    await pool.play(soundId);
  }

  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: APP_scaffold_back_color,
      appBar: AppBar(
        title: Text("聊天设置"),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop(isupdate);
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: const EdgeInsets.all(10),
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12,vertical: 17),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(color:const Color(0xffdddddd), width: 0.5)
                ),
                child: GestureDetector(
                  onTap: () {
                    // Navigator.of(context).push(CupertinoPageRoute(builder: (context) => MinePreviewPage(
                    //   mobile: widget.userInfo.mobile, 
                    //   isneedpop: true,
                    //   onModRemarkName: (name){
                    //     setState(() {
                    //       username = name;
                    //     });
                    //     if(widget.onModRemarkName != null) widget.onModRemarkName(name);
                    //   },
                    // )));
                    push(context, MinePreviewPage(
                      mobile: widget.userInfo.mobile, 
                      isneedpop: true,
                      onModRemarkName: (name){
                        setState(() {
                          username = name;
                        });
                        if(widget.onModRemarkName != null) widget.onModRemarkName(name);
                      },
                    ));
                  },
                  child: Container( // 加一个container方便点击s
                    color: Colors.white,
                    child: Row(
                      children: [
                        CustomCircleAvatar(size: 46, url: widget.userInfo?.avatar,),
                        SizedBox(width: 10,),
                        Expanded(child: Text(username, style: instanceTextStyle(14, APP_font_black),)),
                        SizedBox(width: 10,),
                        Image.asset("assets/my-next.png")
                      ],
                    ),
                  ),
                )
              ),
              SizedBox(height: 10,),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(color:Color(0xffdddddd), width: 0.5)
                ),
                child: Column(
                  children: [
                    MineInfoCell("好友分组", detail:groupName, isShowArrow: true, callback: () async {
                      String name = await push(context, MsgModFriendGroupPage(userInfo: widget.userInfo,));

                      if(name != null) {
                        setState(() {
                          // 跟新好友分组的名字
                          groupName = name;
                        });
                      }
                    },),
                    MineInfoCell("聊天背景", isShowArrow: true, callback: () async {
                      bool update = await push(context, MineBackgroundPage(friendInfo: widget.userInfo,));
                      isupdate = update;
                    },),
                    MineInfoCell("聊天图片", isShowArrow: true,callback: (){
                      push(context, MsgImageHistoryPage(mobile: widget.userInfo.mobile,));
                    }),
                    MineInfoCell("查找聊天记录", isShowArrow: true, callback: (){
                      push(context, MsgHistoryPage(mobile: widget.userInfo.mobile,));
                    },),
                    MineInfoCell("删除聊天记录", isShowArrow: true, callback: (){
                      _showConfirm("确定后\n将删除本地聊天记录", (){
                        SharedUserInfo.instance().then((value){
                          RongcloudImPlugin.clearHistoryMessages(RCConversationType.Private, value.mobile, DateTime.now().millisecondsSinceEpoch, false, (code) => print(code));
                          RongcloudImPlugin.clearHistoryMessages(RCConversationType.Private, widget.userInfo.mobile, DateTime.now().millisecondsSinceEpoch, false, (code) => null);
                        });
                      });
                    },),
                  ],
                ),
              ),
              SizedBox(height: 10,),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(color:Color(0xffdddddd), width: 0.5)
                ),
                child: Column(
                  children: [
                    SettingNotifierCell(title:"特别关心提示音", isopen: isspecialSound, onTap: (val) async {
                      setState(() {
                        isspecialSound = !isspecialSound;
                      });
                      SharedPreferences share = await SharedPreferences.getInstance();
                      List<String> list = share.getStringList(KEY_special_sound) ?? [];
                      isspecialSound ? list.add(widget.userInfo.mobile) : list.remove(widget.userInfo.mobile);
                      if(isspecialSound) _playAudio();
                      share.setStringList(KEY_special_sound, list);
                    }),
                    SizedBox(height: 15,),
                    SettingNotifierCell(title:"消息免打扰", isopen: notifierOpen, onTap: (val) async {
                      setState(() {
                        notifierOpen = !notifierOpen;
                      });
                      SharedPreferences share = await SharedPreferences.getInstance();
                      share.clear();
                      share.setBool(Key_notifer + widget.userInfo.mobile, notifierOpen);
                      RongcloudImPlugin.setConversationNotificationStatus(RCConversationType.Private, widget.userInfo.mobile, notifierOpen, (status, code) => null);
                    },),
                  ],
                ),
              ),
              GestureDetector(
                onTap: (){
                  _showConfirm("确定删除该好友\n并取消关注", _requestDel);
                },
                child: Container(
                  margin: const EdgeInsets.only(top: 60, left: 57, right: 57),
                  width: size.width,
                  padding: const EdgeInsets.symmetric(vertical: 13),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    border: Border.all(color: APP_font_black, width: 0.5),
                    borderRadius: BorderRadius.circular(30)
                  ),
                  child: Text("删除好友", style: instanceTextStyle(14, APP_verify_error_color),),
                ),
              ),
              GestureDetector(
                onTap: (){
                  Navigator.of(context).pushNamed("/msgreport",arguments: widget.userInfo.mobile);
                },
                child: Padding(
                  padding: const EdgeInsets.only(top: 9.0),
                  child: Text("被骚扰了？举报该用户", style: instanceTextStyle(10, APP_main_color),),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  _showConfirm(String msg, Function sure) {
    AlertTool.showConfirmDialog(context, title: msg, sureCallback: sure);
  }
}